// Eno.Application/Services/AuthService.cs
using Eno.Domain.Entity.App;
using Eno.Domain.Repositories;
using Eno.Infrastructure.Services;

namespace Eno.Application.Services;

public interface IAuthService
{
    Task<string> LoginAsync(string account, string password);
    Task<bool> ValidateTokenAsync(string token);
    Task<AppUser?> GetCurrentUserAsync(string token);
}

public class AuthService : IAuthService
{
    private readonly IJwtService _jwtService;
    private readonly IUserRepository<AppUser> _userRepository;

    public AuthService(IJwtService jwtService, IUserRepository<AppUser> userRepository)
    {
        _jwtService = jwtService;
        _userRepository = userRepository;
    }

    public async Task<string> LoginAsync(string account, string password)
    {
        // 验证用户凭据
        var user = await _userRepository.GetUserByAccount(account);
        if (user == null || !VerifyPassword(password, user.Password, user.Salt))
        {
            throw new UnauthorizedAccessException("Invalid credentials");
        }

        // 获取用户角色
        var roles = await _userRepository.GetUserRolesAsync(user.ID);

        // 生成Token
        return _jwtService.GenerateToken(user.ID.ToString(), user.Account, roles);
    }

    public Task<bool> ValidateTokenAsync(string token)
    {
        return Task.FromResult(_jwtService.IsTokenValid(token));
    }

    public async Task<AppUser?> GetCurrentUserAsync(string token)
    {
        var principal = _jwtService.ValidateToken(token);
        if (principal == null) return null;

        var userId = principal.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value;
        if (string.IsNullOrEmpty(userId)) return null;

        return await _userRepository.GetUserByIdAsync(Guid.Parse(userId));
    }

    private bool VerifyPassword(string password, string hash, string salt)
    {
        // 这里应调用你的 PasswordService 或自定义密码校验逻辑
        // 推荐：加盐哈希校验
        var passwordService = new PasswordService();
        return passwordService.VerifyPassword(password, hash, salt);
    }
}

